package com.tank.elk.elasticsearch;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
//import org.elasticsearch.action.ActionWriteResponse;
import org.elasticsearch.action.bulk.*;
import org.elasticsearch.action.delete.DeleteRequestBuilder;
import org.elasticsearch.action.delete.DeleteResponse;
import org.elasticsearch.action.get.GetResponse;
import org.elasticsearch.action.get.MultiGetItemResponse;
import org.elasticsearch.action.get.MultiGetResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.MultiSearchResponse;
import org.elasticsearch.action.search.SearchRequestBuilder;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.action.update.UpdateResponse;
import org.elasticsearch.client.Client;
import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.transport.InetSocketTransportAddress;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.xcontent.XContentBuilder;
//import org.elasticsearch.index.mapper.object.ObjectMapper;
import org.elasticsearch.index.query.QueryBuilders;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;

/**
 * Created with IntelliJ IDEA.
 * User: SuQiEr
 * Date:2017/4/19
 * Time: 11:17
 * To change this template use File | Settings | File Templates.
 */
@Slf4j
public class ElasticsearchDemo1 {

//    private Client client;
//
//    @Before
//    public void connectService() throws UnknownHostException {
//        client = TransportClient.builder().build()
//                .addTransportAddress(new InetSocketTransportAddress( InetAddress.getByName("139.224.226.206"), 9300));
//    }
//
//    @After
//    public void closeConnect(){
//        if(client != null){
//            client.close();
//        }
//    }
//
//    @Test
//    public void  testIndex() throws UnknownHostException {
//
//        for (int i=0; i< 10 ;i++) {
//            Map<String, Object> map = new HashMap<>();
//            map.put("user", "kimchy_"+i);
//            map.put("postDate", new Date());
//            map.put("message", "trying out Elasticsearch_"+i);
//
//            IndexResponse response = client.prepareIndex("twitter", "tweet", ""+i).setSource(JSON.toJSONString(map).getBytes()).get();
//
//            // Index name
//            String _index = response.getIndex();
//            // Type name
//            String _type = response.getType();
//            // Document ID (generated or not)
//            String _id = response.getId();
//            // Version (if it's the first time you index this document, you will get: 1)
//            long _version = response.getVersion();
//            // isCreated() is true if the document is a new one, false if it has been updated
//            boolean created = response.isCreated();
//            log.info("response:{}", JSON.toJSONString(response));
//        }
//
//    }
//
//    @Test
//    public void testGet(){
//        GetResponse response = client.prepareGet("twitter", "tweet", "1").get();
//        log.info("get response:{}", JSON.toJSONString(response));
//    }
//
//    @Test
//    public void testDelete(){
//        DeleteResponse response = client.prepareDelete("twitter", "tweet", "1").get();
//        log.info("delete response:{}", JSON.toJSONString(response));
//    }
//
//    /**
//     * 存在的key为更新，不存在的key为合并
//     * @throws ExecutionException
//     * @throws InterruptedException
//     */
//    @Test
//    public void testUpdate() throws ExecutionException, InterruptedException {
//
//        UpdateRequest updateRequest = new UpdateRequest();
//        updateRequest.index("twitter");
//        updateRequest.type("tweet");
//        updateRequest.id("1");
//        Map<String,Object> map = new HashMap<>();
////        map.put("user", "kimchy_update");
////        map.put("postDate", new Date());
////        map.put("message", "trying out Elasticsearch_update");
//        map.put("merge_field", "merge field to document");
//        updateRequest.doc(JSON.toJSONString(map).getBytes());
//        UpdateResponse updateResponse = client.update(updateRequest).get();
//        log.info("update response:{}", JSON.toJSONString(updateResponse));
//    }
//
//    /**
//     * 更新插入
//     * @throws ExecutionException
//     * @throws InterruptedException
//     */
//    @Test
//    public void testUpsert() throws ExecutionException, InterruptedException {
//
//        Map<String,Object> map = new HashMap<>();
//        map.put("name", "Joe Smith");
//        map.put("gender", "male");
//        IndexRequest indexRequest = new IndexRequest("index", "type", "1").source(JSON.toJSONString(map).getBytes());
//
//        Map<String,String> updateMap = new HashMap<>();
//        updateMap.put("gender", "male_upsert");
//        UpdateRequest updateRequest = new UpdateRequest().index("index").type("type").id("1").doc(JSON.toJSONString(updateMap).getBytes());
//        updateRequest.upsert(indexRequest);
//
//        client.update(updateRequest).get();
//    }
//
//    //多笔查询，结果为每个文档查询的行数
//    @Test
//    public void testMultiGet(){
//        MultiGetResponse multiGetItemResponses =  client.prepareMultiGet().add("twitter","tweet","0","1").
//                add("index","type","1").get();
//        MultiGetItemResponse[] responses = multiGetItemResponses.getResponses();
//        for (MultiGetItemResponse multiGetItemResponse : responses){
//            GetResponse getResponse = multiGetItemResponse.getResponse();
//            if(getResponse.isExists()){
//                String jsonText = getResponse.getSourceAsString();
//                log.info("jsonText:{}",jsonText);
//            }
//        }
//    }
//
//    /**
//     * 批量操作
//     */
//    @Test
//    public void testBulk(){
//
//        Map<String,String> map = new HashMap<>();
//        map.put("gender","male");
//        map.put("name","tank");
//        BulkRequestBuilder bulkRequestBuilder = client.prepareBulk();
//        bulkRequestBuilder.add(client.prepareIndex("index","type","20").setSource(JSON.toJSONString(map).getBytes()));
//        bulkRequestBuilder.add(client.prepareIndex("index","type","21").setSource(JSON.toJSONString(map).getBytes()));
//        BulkResponse bulkItemResponses = bulkRequestBuilder.get();
//       for (BulkItemResponse bp:bulkItemResponses.getItems()){
//           log.info("bp:{}", JSON.toJSONString(bp.getResponse()));
//       }
//    }
//
//
//    @Test
//    public void testBulkProcessor() throws InterruptedException {
//
//        BulkProcessor bulkProcessor = BulkProcessor.builder(client, new BulkProcessor.Listener() {
//
//            @Override
//            public void beforeBulk(long executionId, BulkRequest request) {
//                    log.info("请求前executionId:{}", executionId);
//            }
//
//            @Override
//            public void afterBulk(long executionId, BulkRequest request, BulkResponse response) {
//                log.info("请求后executionId:{}", executionId);
//            }
//
//            @Override
//            public void afterBulk(long executionId, BulkRequest request, Throwable failure) {
//                log.info("请求后 发生异常executionId:{}", executionId);
//            }
//        })
//        .setBulkActions(10000)
//        .setBulkSize(new ByteSizeValue(1, ByteSizeUnit.GB))
//        .setFlushInterval(TimeValue.timeValueSeconds(50)) //定时秒时间内提交
//        .setConcurrentRequests(1)
//        .setBackoffPolicy(
//                BackoffPolicy.exponentialBackoff(TimeValue.timeValueMillis(100), 3))
//        .build();
//
//        //添加批量处理的请求
//        Map<String, String> paramMap = new HashMap<>();
//        paramMap.put("name","tank");
//        bulkProcessor.add(new IndexRequest("index", "type", "104").source(JSON.toJSONString(paramMap).getBytes()));
//        bulkProcessor.add(new IndexRequest("index", "type", "105").source(JSON.toJSONString(paramMap).getBytes()));
//        Thread.sleep(10000);
//    }
//
//    //批量查询
//    @Test
//    public void multiSearchTest(){
//
//        SearchRequestBuilder srb1 = client.prepareSearch().setQuery(QueryBuilders.queryStringQuery("elasticsearch")).setSize(1);
//
//        SearchRequestBuilder srb2 = client.prepareSearch().setQuery(QueryBuilders.matchQuery("name", "kimchy")).setSize(1);
//
//        MultiSearchResponse msr = client.prepareMultiSearch().add(srb1).add(srb2).execute().actionGet();
//
//        long lbHits = 0;
//
//        for (MultiSearchResponse.Item item : msr.getResponses()){
//            SearchResponse response = item.getResponse();
//            lbHits += response.getHits().getTotalHits();
//        }
//
//        log.info("命中率:{}", lbHits);
//    }

}










